"""
Error Handler Middleware
========================

Global error handling for the Flask application.
Provides consistent error responses for different exception types.
"""

import logging
from flask import jsonify
from werkzeug.exceptions import HTTPException
from sqlalchemy.exc import SQLAlchemyError
import jwt

# Initialize logger
logger = logging.getLogger(__name__)

def register_error_handlers(app):
    """
    Register error handlers with the Flask app.
    
    Args:
        app: Flask application instance
    """
    
    @app.errorhandler(404)
    def not_found_error(error):
        """Handle 404 Not Found errors."""
        return jsonify({
            'status': 'error',
            'message': 'Resource not found',
            'error_code': 'not_found',
            'timestamp': datetime.utcnow().isoformat()
        }), 404
    
    @app.errorhandler(405)
    def method_not_allowed_error(error):
        """Handle 405 Method Not Allowed errors."""
        return jsonify({
            'status': 'error',
            'message': 'Method not allowed',
            'error_code': 'method_not_allowed',
            'timestamp': datetime.utcnow().isoformat()
        }), 405
    
    @app.errorhandler(500)
    def internal_error(error):
        """Handle 500 Internal Server errors."""
        logger.error(f"Internal server error: {str(error)}")
        return jsonify({
            'status': 'error',
            'message': 'Internal server error',
            'error_code': 'internal_error',
            'timestamp': datetime.utcnow().isoformat()
        }), 500
    
    @app.errorhandler(SQLAlchemyError)
    def database_error(error):
        """Handle database errors."""
        logger.error(f"Database error: {str(error)}")
        return jsonify({
            'status': 'error',
            'message': 'Database operation failed',
            'error_code': 'database_error',
            'timestamp': datetime.utcnow().isoformat()
        }), 500
    
    @app.errorhandler(jwt.ExpiredSignatureError)
    def expired_token_error(error):
        """Handle expired JWT tokens."""
        return jsonify({
            'status': 'error',
            'message': 'Token has expired',
            'error_code': 'token_expired',
            'timestamp': datetime.utcnow().isoformat()
        }), 401
    
    @app.errorhandler(jwt.InvalidTokenError)
    def invalid_token_error(error):
        """Handle invalid JWT tokens."""
        return jsonify({
            'status': 'error',
            'message': 'Invalid token',
            'error_code': 'invalid_token',
            'timestamp': datetime.utcnow().isoformat()
        }), 401
    
    @app.errorhandler(HTTPException)
    def http_error(error):
        """Handle HTTP exceptions."""
        return jsonify({
            'status': 'error',
            'message': error.description or 'HTTP error',
            'error_code': f'http_{error.code}',
            'timestamp': datetime.utcnow().isoformat()
        }), error.code
    
    @app.errorhandler(Exception)
    def unhandled_error(error):
        """Handle unhandled exceptions."""
        logger.error(f"Unhandled error: {str(error)}", exc_info=True)
        return jsonify({
            'status': 'error',
            'message': 'An unexpected error occurred',
            'error_code': 'unexpected_error',
            'timestamp': datetime.utcnow().isoformat()
        }), 500